import { Pipe, PipeTransform, Injectable} from '@angular/core';
import {isString, isFunction} from '../common';

@Pipe({
    name: 'orderBy', pure: true
})
@Injectable()
export class OrderByPipe implements PipeTransform {

    transform(array: Array<any>, expression: string | Function, reverse = false): Array<any> {
        array.sort((a: any, b: any) => {
            let c = this.expressionData(a, expression);
            let d = this.expressionData(b, expression);

            if (c < d) {
                return reverse ? 1 : -1;
            } else if (c > d) {
                return reverse ? -1 : 1;
            } else {
                return 0;
            }
        });
        return array;
    }

    private expressionData(data: any, expression: any) {
        if (isString(expression)) {
            return data[expression];
        }

        if (isFunction(expression)) {
            return expression(data);
        }

        return data;
    }
}